﻿using AuthCenter.API.Application.Command.Account;
using AuthCenter.Domain;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.Account
{
    public class DelAccountHandler : IRequestHandler<DelAccountCommand, APIResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<LogModel> logRepo;

        public DelAccountHandler(IBaseRepository<AccountModel> accountRepo,
                                 IBaseRepository<LogModel> logRepo)
        {
            this.accountRepo = accountRepo;
            this.logRepo = logRepo;
        }
        public Task<APIResult<int>> Handle(DelAccountCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = accountRepo.GetAll().FirstOrDefault(x=>x.Id == request.Id);
            if (res == null)
            {
                result.Message = "找不到此编号";
                result.Code = APIEnum.Ok;
                return Task.FromResult(result);
            }
            res.IsDel = true;
            LogModel log = new LogModel()
            {
                Id = YitIdHelper.NextId(),
                CreateDate = DateTime.Now,
                LogContent = "用户删除成功"
            };
            int r = 0;
            int r1 = 0;
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    r = accountRepo.UpdateAsync(res).Result;
                    r1 = logRepo.AddAsync(log).Result;
                    tran.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
            }
            if (r > 0)
            {
                result.Message = "用户删除成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "用户删除失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
